package com.gzx.qc.core.config;

import cn.hutool.core.collection.CollectionUtil;
import com.gzx.qc.core.enums.GzxQaKeyWordScopeEnum;
import com.gzx.qc.modular.keyword.service.GzxQaKeywordService;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zjt
 * @description
 * @date 2025/1/24 16:00
 */
@Component
public class QaKeywordInitializationConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private GzxQaKeywordService qaKeywordService;

    // 使用 AtomicReference 管理不可变集合的引用
    private final AtomicReference<Set<String>> agentKeywordSet = new AtomicReference<>(Collections.emptySet());
    private final AtomicReference<Set<String>> customerKeywordSet = new AtomicReference<>(Collections.emptySet());
    private final AtomicReference<Set<String>> allKeywordSet = new AtomicReference<>(Collections.emptySet());

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        loadDataFromDatabase();
    }

    /**
     * 定时任务，每隔一段时间重新加载数据。
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void scheduleLoadData() {
        loadDataFromDatabase();
    }

    private void loadDataFromDatabase() {
        loadKeyWord(GzxQaKeyWordScopeEnum.AGENT.getCode());
        loadKeyWord(GzxQaKeyWordScopeEnum.CUSTOMER.getCode());
        loadKeyWord(GzxQaKeyWordScopeEnum.TWO_PARTIES.getCode());
    }

    private void loadKeyWord(Integer type) {
        Set<String> newKeywordList = qaKeywordService.listAllKeyword(type);
        Set<String> newSet = ConcurrentHashMap.newKeySet();
        newSet.addAll(newKeywordList);
        if (type.equals(GzxQaKeyWordScopeEnum.AGENT.getCode())) {
            agentKeywordSet.set(Set.copyOf(newKeywordList));
        }
        if (type.equals(GzxQaKeyWordScopeEnum.CUSTOMER.getCode())) {
            customerKeywordSet.set(Set.copyOf(newKeywordList));
        }
        if (type.equals(GzxQaKeyWordScopeEnum.TWO_PARTIES.getCode())) {
            allKeywordSet.set(Set.copyOf(newKeywordList));
        }
        // 重新加载自定义词典
        newKeywordList.forEach(CustomDictionary::add);
        CustomDictionary.reload();
    }

    public Set<String> verifyKeyWord(Integer speakerRole, Set<String> contentKeySet) {
        Set<String> keywordSet = new HashSet<>(getIntersection(allKeywordSet.get(), contentKeySet));
        if (speakerRole == 1) {
            keywordSet.addAll(getIntersection(customerKeywordSet.get(), contentKeySet));
        }
        if (speakerRole == 2) {
            keywordSet.addAll(getIntersection(agentKeywordSet.get(), contentKeySet));
        }
        return keywordSet;
    }

    //质检所有关键字关键字
    public Set<String> loadKeyWord() {
        Set<String> keywordSet = new HashSet<>();
        Set<String> agentKeys = qaKeywordService.listAllKeyword(GzxQaKeyWordScopeEnum.AGENT.getCode());
        keywordSet.addAll(agentKeys);
        Set<String> customerKeys = qaKeywordService.listAllKeyword(GzxQaKeyWordScopeEnum.CUSTOMER.getCode());
        keywordSet.addAll(customerKeys);
        Set<String> towKeys = qaKeywordService.listAllKeyword(GzxQaKeyWordScopeEnum.TWO_PARTIES.getCode());
        keywordSet.addAll(towKeys);
        return keywordSet;
    }

    public boolean isExitsKeyword(Integer speakerRole, Set<String> contentKeySet) {
        if (speakerRole == 1) {
            return CollectionUtil.isNotEmpty(getIntersection(agentKeywordSet.get(), contentKeySet)) ||
                    CollectionUtil.isNotEmpty(getIntersection(allKeywordSet.get(), contentKeySet));
        }
        if (speakerRole == 2) {
            return CollectionUtil.isNotEmpty(getIntersection(customerKeywordSet.get(), contentKeySet)) ||
                    CollectionUtil.isNotEmpty(getIntersection(allKeywordSet.get(), contentKeySet));
        }
        return false;
    }

    /**
     * 获取两个集合的交集
     *
     * @param setA 总集合
     * @param setB 子集合
     * @return 交集集合
     */
    public static Set<String> getIntersection(Set<String> setA, Set<String> setB) {
        // 创建 setA 的副本，避免修改原始集合
        Set<String> intersection = new HashSet<>(setA);
        // 保留与 setB 共有的元素
        intersection.retainAll(setB);
        return intersection;
    }
}